package org.sqp.proxy.impl;

import okhttp3.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.sqp.conn.Browser;
import org.sqp.conn.BrowserFactory;
import org.sqp.proxy.AbstractNetProxyService;
import org.sqp.proxy.model.NetProxy;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author sunqipeng
 * @date 2019/1/2
 */
public class KuaiDaiLiHttpProxyService extends AbstractNetProxyService {
    private Browser browserInstance;
    private int reqSum = 0;
    private int page = 1;

    public KuaiDaiLiHttpProxyService() {
        browserInstance = BrowserFactory.getDefaultBrowser();
    }

    public long getMinInterval() {
        return 3333;
    }

    public List<NetProxy> netAcquire() {
        List<NetProxy> list = new ArrayList<>();
        if (reqSum++ >= 100) {
            browserInstance = BrowserFactory.getDefaultBrowser();
        }

        try {
            Response resp = browserInstance.request(browserInstance.getRequestBuilder().url("https://www.kuaidaili.com/free/inha/" + page++).build());
            Document doc = Jsoup.parse(resp.body().string());
            Elements elements = doc.select("#list tbody tr");
            for (Element tr:elements){
                Elements td1 = tr.select("td:nth-child(1)");
                Elements td2 = tr.select("td:nth-child(2)");
                Elements td5 = tr.select("td:nth-child(5)");
                String ip = td1.text();
                String port = td2.text();
                String loc = td5.text();
                NetProxy proxy = new NetProxy();
                proxy.setIp(ip);
                proxy.setLocation(loc);
                proxy.setPort(Integer.parseInt(port));
                list.add(proxy);
            }

        }catch (Exception e){
            // nothing
        }
        return list;
    }


}
